package check

import (
	"bufio"
	"encoding/csv"
	"golang.org/x/text/encoding/charmap"
	"golang.org/x/text/transform"
	"io"
	"log"
	"os"
)

func ReadCsv(filepath string, encoding string) ([][]string, error) {
	// 打开CSV文件
	file, err := os.Open(filepath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	// 创建一个BufferedReader来读取文件
	buf := bufio.NewReader(file)

	var reader io.Reader = buf
	var e encoding.Encoding = encoding.Nop // 默认使用nop编码器，即不进行编码转换

	switch encoding {
	case "utf-8":
		// UTF-8不需要特殊处理
	case "gbk":
		e = charmap.GBK
	case "iso-8859-1":
		e = charmap.ISO8859_1
	// 可以添加更多的编码支持
	default:
		return nil, log.Fatalf("Unsupported file encoding: %s", encoding)
	}

	if e != encoding.Nop {
		reader = transform.NewReader(buf, e.NewDecoder())
	}

	// 读取CSV文件
	csvReader := csv.NewReader(reader)
	records, err := csvReader.ReadAll()
	if err != nil {
		return nil, err
	}

	return records, nil
}
